package com.nxk.modules.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nxk.modules.core.dao.SysLogDao;
import com.nxk.modules.core.entity.SysLog;
import com.nxk.modules.core.entity.SysUser;
import com.nxk.modules.core.service.SysLogService;
import com.nxk.modules.core.service.SysUserService;
import com.nxk.modules.utils.CommonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.UUID;

@Service
public class SysLogServiceImpl extends ServiceImpl<SysLogDao, SysLog> implements SysLogService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysLogDao sysLogDao;

    @Override
    @Transactional(readOnly = false)
    public void saveLog(SysLog sysLog,HttpServletRequest request) {
        QueryWrapper<SysUser> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("login_code",sysLog.getLoginCode());
        SysUser sysUser = sysUserService.getOne(queryWrapper);
        if (sysUser!=null){
            sysLog.setId(UUID.randomUUID().toString());
            sysLog.setUserNick(sysUser.getUserNick());
            sysLog.setLoginTime(new Date());
            sysLog.setClientIp(CommonUtils.getIpAddr(request));
            sysLog.setBrowserName(CommonUtils.getBrowserName(request));
            sysLogDao.saveLog(sysLog);
        }
    }

    @Override
    public IPage<SysLog> page(SysLog sysLog) {
        Page<SysLog> page = new Page<SysLog>(sysLog.getPageNo(), sysLog.getPageSize());
        QueryWrapper<SysLog> queryWrapper=new QueryWrapper<SysLog>();
        if (StringUtils.isNotBlank(sysLog.getLoginCode())){
            queryWrapper.lambda().like(SysLog::getLoginCode,sysLog.getLoginCode());
        }
        queryWrapper.orderByAsc("sort").in("status",1,2);
        IPage<SysLog> result = super.page(page, queryWrapper);
        return result;
    }







}
